<template>
  <view class="page over_hidden bg-white">
    <!-- #ifdef APP-PLUS || H5 -->
    <view :id="option.id"
          :option="option"
          :treeDom="treeDom"
          :change:treeDom="treeGraph.changeTreeGraphSize"
          :change:option="treeGraph.changeTreeGraphData"
          style="width: 100%;height: 100%;over"></view>
    <!-- #endif -->
    <!-- #ifndef APP-PLUS || H5 -->
    <view>非 APP、H5 环境不支持</view>
    <!-- #endif -->
  </view>
</template>

<script>
import treeData1 from "./data2";
export default {
	props:{
		treeData:{
			type:Object,
			default:()=>({})
		}
	},
	computed:{
		option(){
			return{
				id: "canvasId",
				data: uni.getStorageSync('tpData')
			}
		}
	},
  data() {
    return {
      treeDom: {
        width: 375,
        height: 500,
      },
    };
  },
  mounted() {
	// let windowHeight = 500
	// if(uni.getStorageSync('windowHeight')){
	// 	windowHeight = uni.getStorageSync('windowHeight')
	// }else{
	// 	let sysInfo = uni.getWindowInfo()
	// 	windowHeight = sysInfo.windowHeight
	// 	uni.setStorageSync('windowHeight',sysInfo.windowHeight)
	// }
	// this.treeData.height = windowHeight - 240
    uni
      .createSelectorQuery()
      .select("#canvasId")
      .boundingClientRect((data) => {
        this.treeDom = data;
      })
      .exec();
  },
  methods: {},
};
</script>

<script module="treeGraph" lang="renderjs">
import F6 from '@/static/js/F6/f6.min.js'
import TreeGraph from '@/static/js/F6/extends/graph/treeGraph.js'
F6.registerGraph('TreeGraph', TreeGraph)

const COLLAPSE_ICON = function COLLAPSE_ICON(x, y, r) {
  return [
    ['M', x - r, y - r],
    ['a', r, r, 0, 1, 0, r * 2, 0],
    ['a', r, r, 0, 1, 0, -r * 2, 0],
    ['M', x + 2 - r, y - r],
    ['L', x + r - 2, y - r],
  ];
};
const EXPAND_ICON = function EXPAND_ICON(x, y, r) {
  return [
    ['M', x - r, y - r],
    ['a', r, r, 0, 1, 0, r * 2, 0],
    ['a', r, r, 0, 1, 0, -r * 2, 0],
    ['M', x + 2 - r, y - r],
    ['L', x + r - 2, y - r],
    ['M', x, y - 2 * r + 2],
    ['L', x, y - 2],
  ];
};

const defaultStateStyles = {
  hover: {
    stroke: '#1890ff',
    lineWidth: 2,
  },
};

const defaultNodeStyle = {
  // fill: '#fff',
  // stroke: '',
  radius: 5,
  
};

const defaultEdgeStyle = {
  stroke: '#0bb976',
  endArrow: {
    path: 'M 0,0 L 12, 6 L 9,0 L 12, -6 Z',
    fill: '#0bb976',
    d: -20,
  },
};

const defaultLayout = {
  type: 'compactBox',
  direction: 'TB',
  getId: function getId(d) {
    return d.id;
  },
  getHeight: function getHeight() {
    return 16;
  },
  getWidth: function getWidth() {
    return 16;
  },
  getVGap: function getVGap() {
    return 40;
  },
  getHGap: function getHGap() {
    return 70;
  },
};

const defaultLabelCfg = {
  style: {
    fill: '#333',
    fontSize: 10
  },
};

export default {
  data() {
    return {
      graph: null,  
	  logoMap:{
	  	"其他":require('../static/qita.png'),
	  	"抓拍相机":require('../static/zhuapaixiangji.png'),
	  	"枪机": require('../static/qiangji.png'),
	  	"球机": require('../static/qiuji.png'),
	  	"硬盘录像机": require('../static/yingpanluxiangji.png'),
	  	"无线网桥": require('../static/wangqiao.png'),
	  	"智能路由": require('../static/zhinengluyou.png'),
	  	"综合配电箱": require('../static/zonghepeidianxiang.png'),
	  	"运维助手" :require('../static/ywzs.jpeg'),
		"摄像机":require('../static/jiankongnew.png')
	  }
    }
  },  
  mounted() {
    // if (typeof window.F6 === 'function') {
		
      this.init()
    // } else {
    	// 动态引入较大类库避免影响页面展示
    	// const script = document.createElement('script')
    	// view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
    	// script.src = 'https://gw.alipayobjects.com/os/antv/pkg/_antv.f6-{$version}/dist/f6.js'
    	// script.onload = this.init.bind(this)
    	// document.head.appendChild(script)
    // }
  },
  methods: {
    init() {
	  var that = this
	  var canvas = document.createElement('canvas');
	  var context = canvas.getContext('2d');
	  
	  var img = new Image();
	  img.crossOrigin = '';
	  img.onload = function () {
	      context.drawImage(this, 0, 0);
	      context.getImageData(0, 0, this.width, this.height);
	  };
	  // img.src = require('../static/ywzs.jpeg')
      F6.Util.traverseTree(this.option.data, (d) => {
		  
        d.leftIcon = {
          style: {
            fill: '#fff',
            stroke: '#fff',
          },
		  img:img,
          
        };
        return true;
      });

      F6.registerNode( 'icon-node', {
          options: {
            size: [60, 20],
            stroke: '#0bb976',
            fill: '#0bb976',
          },
          draw(cfg, group) {
            const styles = this.getShapeStyle(cfg);
			
            const { labelCfg = {} } = cfg;
			
            const w = styles.width;
            const h = styles.height;

            const keyShape = group.addShape('rect', {
              attrs: {
                ...styles,
                x: -w / 2,
                y: -h / 2,
              },
            });

            /**
             * leftIcon 格式如下：
             *  {
             *    style: ShapeStyle;
             *    img: ''
             *  }
             */
			if(!cfg.logo){
				cfg.logo = '其他'
			}
            if (cfg.logo) {
			  let imgSrc = that.logoMap[cfg.logo]
			  if(!imgSrc){
				imgSrc = require('../static/qita.png')
			  }
              const { style, imgs } = cfg.logo;
			  var img = new Image();
			  img.crossOrigin = '';
			  img.onload = function () {
			      context.drawImage(this, 0, 0);
			      context.getImageData(0, 0, this.width, this.height);
			  };
			  
			  img.src = imgSrc
              group.addShape('rect', {
                attrs: {
                  x: 10 - w / 2,
                  y: 10 - h / 2,
                  width: 38,
                  height: styles.height - 16,
                  fill: '#fff',
                  ...style,
                },
              });
              group.addShape('image', {
                attrs: {
                  x: 20 - w / 2,
                  y: 10 - h / 2,
                  width: 24,
                  height: 24,
                  img:
                    img ||
                    'https://g.alicdn.com/cm-design/arms-trace/1.0.155/styles/armsTrace/images/TAIR.png',
                },
                name: 'image-shape',
              });
            }

            // 如果不需要动态增加或删除元素，则不需要 add 这两个 marker
            // group.addShape('marker', {
            //   attrs: {
            //     x: 40 - w / 2,
            //     y: 52 - h / 2,
            //     r: 6,
            //     stroke: '#73d13d',
            //     cursor: 'pointer',
            //     symbol: EXPAND_ICON,
            //   },
            //   name: 'add-item',
            // });

            // group.addShape('marker', {
            //   attrs: {
            //     x: 80 - w / 2,
            //     y: 52 - h / 2,
            //     r: 6,
            //     stroke: '#ff4d4f',
            //     cursor: 'pointer',
            //     symbol: COLLAPSE_ICON,
            //   },
            //   name: 'remove-item',
            // });

            if (cfg.label) {
              group.addShape('text', {
                attrs: {
                  ...labelCfg.style,
                  text: cfg.label,
                  x: 8 - w / 2,
                  y:  20,
                },
              });
            }
			
			if (cfg.onlineText) {
			  group.addShape('text', {
			    attrs: {
			      ...labelCfg.style,
			      text: cfg.onlineText,
				  fill: '#ff4d4f',
				  border:'#ff4d4f',
				  align:'center',
				  size:12,
			      x: 8 - w / 2,
			      y: 36,
			    },
			  });
			}

            return keyShape;
          },
          update: undefined,
        }, 'rect');

      F6.registerEdge('flow-line', {
        draw(cfg, group) {
          const { startPoint } = cfg;
          const { endPoint } = cfg;

          const { style } = cfg;
          const shape = group.addShape('path', {
            attrs: {
              stroke: style.stroke,
              endArrow: style.endArrow,
              path: [
                ['M', startPoint.x, startPoint.y],
                ['L', startPoint.x, (startPoint.y + endPoint.y) / 2],
                ['L', endPoint.x, (startPoint.y + endPoint.y) / 2],
                ['L', endPoint.x, endPoint.y],
              ],
            },
          }); 
          return shape;
        },
      });

      this.graph = new F6.TreeGraph({
        container: this.option.id,
        width: this.treeDom.width,
        height: this.treeDom.height,
        animate: true,
        fitView: true, // 画布自适应
        fitCenter: true, //图将会被平移，图的中心将对齐到画布中心，但不缩放。优先级低于 fitView。
        linkCenter: true, //指定边是否连入节点的中心
        modes: {
          default: ['drag-canvas', 'zoom-canvas'],
        },
        defaultNode: {
          type: 'icon-node',
          size: [60, 60],
          style: defaultNodeStyle,
          labelCfg: defaultLabelCfg,
        },
        defaultEdge: {
          type: 'flow-line',
          style: defaultEdgeStyle,
        },
        nodeStateStyles: defaultStateStyles,
        edgeStateStyles: defaultStateStyles,
        layout: defaultLayout
      })
      // 监听
      this.graph.on('node:mouseenter', (evt) => {
        const { item } = evt;
        this.graph.setItemState(item, 'hover', true);
      });

      this.graph.on('node:mouseleave', (evt) => {
        const { item } = evt;
        this.graph.setItemState(item, 'hover', false);
      });

      this.graph.on('node:tap', (evt) => {
        const { item, target } = evt;
        const targetType = target.get('type');
        const name = target.get('name');
		console.log('cccccc',item)
        // 增加元素
        if (targetType === 'marker') {
          const model = item.getModel();
          if (name === 'add-item') {
            if (!model.children) {
              model.children = [];
            }
            const id = `n-${Math.random()}`;
            model.children.push({
              id,
              label: id.substr(0, 8),
              leftIcon: {
                style: {
                  fill: '#e6fffb',
                  stroke: '#e6fffb',
                },
                img:
                  'https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Q_FQT6nwEC8AAAAAAAAAAABkARQnAQ',
              },
            });
            this.graph.updateChild(model, model.id);
          } else if (name === 'remove-item') {
            this.graph.removeChild(model.id);
          }
        }
      });

      this.graph.data(this.option.data);
      this.graph.render(); 
    },
    changeTreeGraphSize() { 
      this.graph.changeSize(this.treeDom.width, this.treeDom.height)
      this.graph.render(); 
      this.graph.fitView()
    }
  }
}
</script>
<style lang="scss" scoped>
.btn_flex {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  padding: 20rpx;
  .btn {
    padding: 10rpx 20rpx;
    background-color: #293ed4;
    border-radius: 10rpx;
    font-size: 24rpx;
    color: #fff;
    margin-left: 10rpx;
    margin-bottom: 10rpx;
  }
}
</style>
